<?php

namespace App\Http\Controllers;

/*
 * 请求
 */

use GuzzleHttp\Client;

class Requery
{
    protected $app_id = 'eventist';
    protected $method = '';
    protected $format = 'json';
    protected $charset = 'utf-8';
    protected $sign_type = 'md5';
    protected $sign = '';
    protected $timestamp = '';
    protected $version = '1.0.0';
    protected $apiSecret = 'fz7msj3cin';
    protected $content = '';
    protected $url = 'https://eretailapi.yuexiuproperty.cn/CRM/fzapi.ashx';
    public function __construct($method,$content,$time,$url='https://eretailapi.yuexiuproperty.cn/CRM/fzapi.ashx')
    {
        $this->method = $method;
        $this->content = json_encode($content);
        $this->timestamp = $time;
        $this->url = $url;
    }

    public function getSign(){
        $data = array();
        $data['timestamp']    = $this->timestamp;
        $data['method']     =  $this->method;
        $data['app_id'] = $this->app_id;
        $data['charset']          = $this->charset;
        $data['sign_type']          = $this->sign_type;
        $data['version']          = $this->version;
        $data['format']          = $this->format;
        $data['apiSecret']          = $this->apiSecret;
        $data['content']          = $this->content;

        ksort($data );

        $s = '';
        foreach ($data as $key => $value)
        {
            $s.= $key.'='.$value.'&';
        }
            $s = substr($s, 0,strlen($s) -1);
            return strtolower(md5($s));
    }

    public function getParam($sign,$time){
        $data = array();
        $data['timestamp']    = $time;
        $data['method']     = $this->method;
        $data['app_id'] = $this->app_id;
        $data['charset']          = $this->charset;
        $data['sign_type']          = $this->sign_type;
        $data['version']          = $this->version;
        $data['format']          = $this->format;
        $data['sign']          = $sign;
        $data['content']          = $this->content;
        return $data;
    }

    public function getSendUrl(){
        return $this->url;
    }



    public function query($time){
        $sign = $this->getSign();
        $sendUrl = $this->getSendUrl();
        $param = $this->getParam($sign,$time);
        $client = new Client();
        $res = $client->request('POST', $sendUrl, [
            'form_params' => $param
        ]);
        $result  =  $res->getBody()->getContents();
        return json_decode($result,true);
    }

}
